package com.zhiyou100.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo5 {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Class<User> userClass = User.class;
        //获取所有公开的方法（自身以及父类的）
        Method[] methods = userClass.getMethods();
        //根据方法名称以及参数列表类型获取对应的方法对象
        Method method = userClass.getDeclaredMethod("setUsername", String.class);
        Method method2 = userClass.getMethod("setAge", int.class);
        //获取自身所有的方法
        Method[] declaredMethods = userClass.getDeclaredMethods();
        for (Method dm : declaredMethods) {
            String name = dm.getName();
            System.out.println("方法名称 = " + name);
            Class<?>[] types = dm.getParameterTypes();
            for (Class<?> type : types) {
                System.out.println("参数类型：" + type);
            }
            Class<?> type = dm.getReturnType();
            System.out.println("返回值类型 = " + type);
        }
        //方法的执行   调用的是setUsername
        User user = new User();
        method.invoke(user,"xueyin");
        System.out.println("user = " + user);

    }
}
